<template>
  <div>
    <div class="toolbar">
      <!-- 按钮操作区 -->
      <div
        class="action-buttons"
        style="margin-bottom: 12px; display: flex; flex-wrap: wrap; gap: 10px"
      >
        <el-button type="primary" @click="dialogVisible = true">
          <el-icon><Plus /></el-icon> 新增OTD记录
        </el-button>

        <el-button type="primary" plain @click="downloadTemplate">
          <el-icon><Download /></el-icon> 下载导入模板
        </el-button>

        <el-upload
          action="http://10.0.8.42:8089/api/otd/batchImport"
          accept=".xlsx"
          :show-file-list="false"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
        >
          <el-button type="primary">批量导入 Excel</el-button>
        </el-upload>

        <el-button type="primary" @click="handleExport">
          <el-icon><Download /></el-icon> 导出
        </el-button>
      </div>

      <!-- 筛选表单区 -->
      <el-form :inline="true" label-width="0" class="filter-form">
        <el-form-item>
          <el-input
            v-model="lotIdFilter"
            placeholder="请输入工卡号"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-input
            v-model="deviceFilter"
            placeholder="请输入产品型号"
            clearable
            style="width: 180px"
          />
        </el-form-item>

        <el-form-item>
          <el-select
            v-model="wipOptnCodeFilter"
            placeholder="请选择当前站点"
            clearable
            style="width: 180px"
            @change="fetchOTDRecords"
          >
            <el-option
              v-for="item in wipOptnCodeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="fetchOTDRecords">搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格展示区 -->
    <el-table
      :data="rows"
      stripe
      border
      class="otd-table"
      empty-text="暂无数据，请点击左上角新增"
    >
      <el-table-column label="序号" prop="id" width="20" v-if="false" />
      <el-table-column label="上海客户代码" prop="custCode" width="120" sortable/>
      <el-table-column label="产品型号" prop="device" width="120" sortable/>
      <el-table-column label="工卡号" prop="lotId" width="120" sortable/>
      <el-table-column label="当前站点" prop="wipOptnCode" width="120" sortable/>
      <el-table-column label="晶圆尺寸" prop="waferSize" width="100" sortable/>
      <el-table-column label="延迟分类" prop="delayCategory" width="150" sortable/>
      <el-table-column label="备注" prop="remark" sortable/>
      <el-table-column
        label="创建时间"
        prop="createTime"
        :formatter="row => formatDate(row.createTime)"
        sortable
      />
      <el-table-column label="状态" prop="isDone" width="100" sortable>
        <template #default="{ row }">
          <el-tag :type="row.isDone == 1 ? 'success' : 'info'">
            {{ row.isDone == 1 ? "已完成" : "未完成" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="140" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="editRow(row)">
            <el-icon><Edit /></el-icon> 编辑
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="deleteRow(row.id, row.lotId)"
          >
            <el-icon><Delete /></el-icon>
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="example-pagination-block">
      <el-pagination
        v-model:current-page="page"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 40, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 弹窗：新增表单 -->
    <el-dialog v-model="dialogVisible" title="新增OTD记录" width="700px" center>
      <el-form :model="form" label-width="120px" label-position="left">
        <el-form-item label="工卡号">
          <el-input
            v-model="form.lotId"
            placeholder="请输入工卡号"
            @blur="fetchLotDetails"
          />
        </el-form-item>
        <el-form-item label="客户代码">
          <el-input v-model="form.custCode" disabled />
        </el-form-item>
        <el-form-item label="产品型号">
          <el-input v-model="form.device" disabled />
        </el-form-item>
        <el-form-item label="当前站点">
          <el-input v-model="form.wipOptnCode" />
        </el-form-item>
        <el-form-item label="晶圆尺寸">
          <el-input v-model="form.waferSize" disabled />
        </el-form-item>
        <el-form-item label="延迟分类">
          <el-select v-model="form.delayCategory" placeholder="请选择延迟分类">
            <el-option label="针卡报修" value="针卡报修" />
            <el-option label="临时变更排产" value="临时变更排产" />
            <el-option label="HoldLot释放列队" value="HoldLot释放列队" />
            <el-option label="无测试资源" value="无测试资源" />
            <el-option label="setup fail" value="setup fail" />
            <el-option label="计划强行投料" value="计划强行投料" />
            <el-option label="工程管控" value="工程管控"/>
            <el-option label="客户通知停止测试" value="客户通知停止测试"/>
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAdd">确定添加</el-button>
      </template>
    </el-dialog>

    <!-- 弹窗：编辑表单 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑OTD记录"
      width="700px"
      center
    >
      <el-form :model="editForm" label-width="120px" label-position="left">
        <el-form-item label="工卡号">
          <el-input v-model="editForm.lotId" disabled />
        </el-form-item>
        <el-form-item label="客户代码">
          <el-input v-model="editForm.custCode" disabled />
        </el-form-item>
        <el-form-item label="产品型号">
          <el-input v-model="editForm.device" disabled />
        </el-form-item>
        <el-form-item label="当前站点">
          <el-input v-model="editForm.wipOptnCode" />
        </el-form-item>
        <el-form-item label="晶圆尺寸">
          <el-input v-model="editForm.waferSize" disabled />
        </el-form-item>
        <el-form-item label="延迟分类">
          <el-input v-model="editForm.delayCategory" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.isDone" placeholder="请选择状态">
            <el-option label="已完成" value="1" />
            <el-option label="未完成" value="0" />
          </el-select>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmEdit">确定修改</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from "vue";
import { ElMessage, ElLoading, ElMessageBox } from "element-plus";
import { Plus, Download, Delete, Edit } from "@element-plus/icons-vue";
import axios from "axios";

// 表格数据
const rows = ref([]);
// 分页相关
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 搜索条件
const lotIdFilter = ref("");
const deviceFilter = ref(""); // 新增产品型号筛选
const wipOptnCodeFilter = ref(""); // 新增当前站点筛选

// 当前站点选项
const wipOptnCodeOptions = ref([]);

// 原始数据（用于前端筛选和分页）
const allRecords = ref([]);

// 表单弹窗控制
const dialogVisible = ref(false);
const editDialogVisible = ref(false); // 控制编辑弹窗

// 当前表单模型
const form = reactive({
  lotId: "",
  custCode: "",
  device: "",
  wipOptnCode: "",
  waferSize: "",
  delayCategory: "",
  remark: ""
});

// 当前编辑表单模型
const editForm = reactive({
  id: null,
  lotId: "",
  custCode: "",
  device: "",
  wipOptnCode: "",
  waferSize: "",
  delayCategory: "",
  remark: "",
  isDone: ""
});

// API 接口定义
const API_OTD_ADD = "http://10.0.8.42:8089/api/otd/create";
const API_OTD_QUERY = "http://10.0.8.42:8089/api/otd/query";
const API_OTD_GET_LOT_DETAILS = "http://10.0.8.42:8089/api/otd/queryDetail";
const API_OTD_EXPORT = "http://10.0.8.42:8089/api/otd/export-Otd";
const API_OTD_DELETE = "http://10.0.8.42:8089/api/otd/";
const API_OTD_UPDATE = "http://10.0.8.42:8089/api/otd";

// const API_OTD_ADD = "https://localhost:44389/api/otd/create";
// const API_OTD_QUERY = "https://localhost:44389/api/otd/query";
// const API_OTD_UPDATE = "https://localhost:44389/api/otd"; // wyh新增
// const API_OTD_GET_LOT_DETAILS = "https://localhost:44389/api/otd/queryDetail";
// const API_OTD_EXPORT = "https://localhost:44389/api/otd/export-Otd";
// const API_OTD_DELETE = "https://localhost:44389/api/otd/";

// 格式化日期
const formatDate = date => {
  if (!date) return "";
  const d = new Date(date);
  if (isNaN(d.getTime())) return date;
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, "0");
  const day = String(d.getDate()).padStart(2, "0");
  const hours = String(d.getHours()).padStart(2, "0");
  const minutes = String(d.getMinutes()).padStart(2, "0");
  const seconds = String(d.getSeconds()).padStart(2, "0");
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

// 根据工卡号获取详细信息
const fetchLotDetails = async () => {
  if (!form.lotId) {
    // 清空相关字段
    form.custCode = "";
    form.device = "";
    form.wipOptnCode = "";
    form.waferSize = "";
    return;
  }
  try {
    const res = await axios.get(API_OTD_GET_LOT_DETAILS, {
      params: { lotId: form.lotId }
    });
    const data = res.data;

    if (data != "cim上未找到开卡记录") {
      form.custCode = data.custCode || "";
      form.device = data.device || "";
      form.wipOptnCode = data.wipOptnCode || "";
      form.waferSize = data.waferSize || "";
    } else {
      ElMessage.warning("cim上未找到开卡记录");
      form.custCode = "";
      form.device = "";
      form.wipOptnCode = "";
      form.waferSize = "";
    }
  } catch (error) {
    console.log(error);
    ElMessage.error(error?.response?.data || "获取工卡号详细信息失败");
  }
};

// 获取当前站点选项
const fetchWipOptnCodeOptions = () => {
  const codes = new Set(allRecords.value.map(item => item.wipOptnCode));
  wipOptnCodeOptions.value = Array.from(codes).filter(Boolean); // 过滤掉空值
};

const downloadTemplate = () => {
  window.open("http://10.0.8.42:8089/static/OTD导入模板.xlsx", "_blank");
};

// 确定添加按钮
const confirmAdd = async () => {
  if (!form.lotId || !form.delayCategory) {
    ElMessage.warning("工卡号和延迟分类必填");
    return;
  }

  if (!form.custCode || !form.device || !form.wipOptnCode || !form.waferSize) {
    ElMessage.warning("客户号、设备号、工序号、晶圆尺寸不能为空");
    return;
  }

  try {
    await axios.post(API_OTD_ADD, {
      lotId: form.lotId,
      custCode: form.custCode,
      device: form.device,
      wipOptnCode: form.wipOptnCode,
      waferSize: form.waferSize,
      delayCategory: form.delayCategory,
      remark: form.remark
    });

    ElMessage.success("添加成功");
    dialogVisible.value = false;

    // 清空表单
    Object.keys(form).forEach(k => (form[k] = ""));

    // 刷新数据
    fetchOTDRecords();
  } catch (error) {
    ElMessage.error(
      error?.response?.data?.message ||
        error?.message ||
        "添加失败，请检查输入或接口状态"
    );
  }
};

// 编辑行
const editRow = row => {
  Object.assign(editForm, row);
  editDialogVisible.value = true;
};

// 确定修改按钮
const confirmEdit = async () => {
  try {
    const payload: any = {
      id: editForm.id,
      remark: editForm.remark,
      isDone: editForm.isDone,
      delayCategory: editForm.delayCategory
    };

    await axios.put(`${API_OTD_UPDATE}/${editForm.id}`, payload, {
      headers: { "Content-Type": "application/json" }
    });

    ElMessage.success("修改成功");
    editDialogVisible.value = false;
    fetchOTDRecords();
  } catch (error) {
    ElMessage.error(
      error?.response?.data?.message ||
        error?.message ||
        "修改失败，请检查输入或接口状态"
    );
  }
};

// 加载分页数据
const fetchOTDRecords = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "加载中...",
    background: "rgba(0,0,0,0.3)"
  });

  try {
    const res = await axios.get(API_OTD_QUERY, {
      params: {
        // 不再发送分页和筛选参数，获取所有数据
        page: 1,
        pageSize: 99999 // 获取足够大的 pageSize 以获取所有数据
      }
    });

    allRecords.value = res.data.items || [];

    // 在前端进行筛选
    let filteredRecords = allRecords.value;
    if (lotIdFilter.value) {
      filteredRecords = filteredRecords.filter(item =>
        item.lotId.includes(lotIdFilter.value)
      );
    }
    if (deviceFilter.value) {
      filteredRecords = filteredRecords.filter(item =>
        item.device.includes(deviceFilter.value)
      );
    }
    if (wipOptnCodeFilter.value) {
      filteredRecords = filteredRecords.filter(
        item => item.wipOptnCode === wipOptnCodeFilter.value
      );
    }

    // 在前端进行分页
    const start = (page.value - 1) * pageSize.value;
    const end = start + pageSize.value;
    rows.value = filteredRecords.slice(start, end);
    total.value = filteredRecords.length;

    // 更新当前站点选项
    fetchWipOptnCodeOptions();
  } catch (error) {
    ElMessage.error(
      error?.response?.data?.message ||
        error?.message ||
        "获取数据失败，请检查接口状态"
    );
  } finally {
    loading.close();
  }
};

// 页码变更时触发
const handlePageChange = newPage => {
  page.value = newPage;
  fetchOTDRecords();
};

const handleSizeChange = newSize => {
  pageSize.value = newSize;
  page.value = 1; // 改变每页大小时重置到第一页
  fetchOTDRecords();
};

// 删除行
const deleteRow = async (id, lotId) => {
  ElMessageBox.confirm(`确定要删除工卡号为 ${lotId} 的记录吗？`, "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        const res = await axios.delete(`${API_OTD_DELETE}${id}`);
        ElMessage.success(res.data.message || "删除成功");
        fetchOTDRecords();
      } catch (err) {
        ElMessage.error(
          err?.response?.data?.message || err?.message || "删除失败"
        );
      }
    })
    .catch(() => {
      // 用户取消
    });
};

// 导出按钮点击事件
const handleExport = async () => {
  const loading = ElLoading.service({
    lock: true,
    text: "导出excel...",
    background: "rgba(0,0,0,0.3)"
  });

  try {
    const response = await axios.get(API_OTD_EXPORT, {
      params: {
        lotId: lotIdFilter.value
      },
      responseType: "blob"
    });

    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
    });

    const downloadUrl = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = downloadUrl;
    link.download = `OTD记录_${new Date().toISOString().slice(0, 19).replace(/[-T:]/g, "")}.xlsx`;
    document.body.appendChild(link);
    link.click();
    link.remove();
    window.URL.revokeObjectURL(downloadUrl);
    ElMessage.success("导出成功！");
  } catch (error) {
    ElMessage.error(
      error?.response?.data?.message ||
        error?.message ||
        "导出失败，请检查接口状态"
    );
  } finally {
    loading.close();
  }
};

const handleUploadSuccess = res => {
  ElMessage.success(
    res?.data?.message || res?.message || "导入成功，请刷新表格查看最新数据"
  );

  fetchOTDRecords();
};

const handleUploadError = error => {
  ElMessage.error(
    error?.response?.data?.message ||
      error?.message ||
      "上传失败，请检查文件格式或网络"
  );
};

// 页面初次加载
onMounted(() => {
  fetchOTDRecords();
});
</script>

<style scoped>
.toolbar {
  display: flex;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 12px;
  align-items: center;
}
.otd-table {
  border-radius: 8px;
  overflow: hidden;
}
.el-dialog__body {
  padding-top: 10px;
  padding-bottom: 0;
}

.example-pagination-block {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
